package learn_concurrent._8;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class T1 {
	static final Logger logger = LoggerFactory.getLogger(T1.class);

	static boolean hasCigarette = false;
	static boolean hasTakeout = false;

	static ReentrantLock ROOM = new ReentrantLock();
	static Condition waitCigaretteSet = ROOM.newCondition();
	static Condition waitTakeoutSet = ROOM.newCondition();

	public static void main(String[] args) throws InterruptedException {

		new Thread(() -> {
			ROOM.lock();
			try {
				logger.info("有烟没？{}", hasCigarette);
				while (!hasCigarette) {
					logger.info("没烟，先歇会！");
					try {
						waitCigaretteSet.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				logger.info("有烟没？{}", hasCigarette);
				logger.info("可以开始干活了！");
			} finally {
				ROOM.unlock();
			}
		}, "小南").start();

		new Thread(() -> {
			ROOM.lock();
			try {
				logger.info("外卖送到没？{}", hasTakeout);
				while (!hasTakeout) {
					logger.info("没外卖，先歇会！");
					try {
						waitTakeoutSet.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				logger.info("外卖送到没？{}", hasTakeout);
				logger.info("可以开始干活了！");
			} finally {
				ROOM.unlock();
			}
		}, "小女").start();

		Thread.sleep(1000);
		new Thread(() -> {
			ROOM.lock();
			try {
				hasTakeout = true;
				logger.info("外卖送到了！");
				waitTakeoutSet.signalAll();
			} finally {
				ROOM.unlock();
			}
		}, "送外卖的").start();

	}

}
